﻿using System.Collections.Generic;
using Deferred.Library.Scene;
using Deferred.Library.Scene.Visual;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Deferred.Library.Deferred
{
    class DirectionalLightRenderEngine
    {
        private DeferredBase deferredBase;
        private Effect directionalLightEffect;
        private IQuadRenderer quadRenderer;

        private EffectParameter cameraPositionParameter;
        private EffectParameter inverseViewProjParameter;
        private EffectParameter lightDirectionParameter;
        private EffectParameter lightColorParameter;
        private EffectParameter lightIntensityParameter;

        public DirectionalLightRenderEngine(DeferredBase deferredBase)
        {
            this.deferredBase = deferredBase;
        }

        public void Initialize()
        {
            directionalLightEffect = deferredBase.Content.InternalContent.Load<Effect>("DirectionalLight");

            cameraPositionParameter = directionalLightEffect.Parameters["cameraPosition"];
            inverseViewProjParameter = directionalLightEffect.Parameters["InverseViewProj"];
            lightDirectionParameter = directionalLightEffect.Parameters["lightDirection"];
            lightColorParameter = directionalLightEffect.Parameters["lightColor"];
            lightIntensityParameter = directionalLightEffect.Parameters["lightIntensity"];

            quadRenderer = (IQuadRenderer)deferredBase.Services.GetService(typeof(IQuadRenderer));
        }

        public void drawDirectionalLights(IList<DirectionalLight> lights, CameraVisual camera)
        {
            cameraPositionParameter.SetValue(camera.Position);
            inverseViewProjParameter.SetValue(Matrix.Invert(camera.View * camera.Projection));
            
            foreach (DirectionalLight light in lights)
            {
                DrawDirectionalLight(light);
            }
        }

        private void DrawDirectionalLight(DirectionalLight light)
        {
            lightDirectionParameter.SetValue(light.Direction);
            lightColorParameter.SetValue(light.Color.ToVector3());
            lightIntensityParameter.SetValue(light.Intensity);

            directionalLightEffect.Begin();
            foreach (EffectPass pass in directionalLightEffect.Techniques["DirectionalLight"].Passes)
            {
                pass.Begin();
                quadRenderer.Render(Vector2.One * -1.0f, Vector2.One);
                pass.End();
            }
            directionalLightEffect.End();
        }
    }
}
